'use client'

import { useEffect, useState, Suspense } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { Bars3Icon, XMarkIcon, PlusIcon, ChevronDownIcon, UserIcon, ChevronRightIcon, FolderIcon, ArchiveBoxIcon } from '@heroicons/react/24/outline'
import NewProjectModal from '@/components/NewProjectModal'
import ProjectSidebar from '@/components/ProjectSidebar'

interface User {
  id: number
  name: string
  email: string
  color: string
  avatar?: string
}

interface Project {
  id: number
  name: string
  description: string
  isArchived: boolean
  created_at: string
}

interface ProjectStats {
  total: number
  待完成: number
  进行中: number
  待测试: number
  已完成: number
  completionRate: number
  projectId: number
  projectName: string
}

interface WorkloadTodo {
  id: number
  content: string
  status: string
  tags: string | null
  created_by: number
  creator_name: string
  creator_color: string
  assigned_to: number | null
  assignee_name: string | null
  assignee_color: string | null
  created_at: string
  project_name: string
}

export default function DashboardPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen bg-gray-100 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">加载中...</p>
        </div>
      </div>
    }>
      <DashboardContent />
    </Suspense>
  )
}

function DashboardContent() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const welcome = searchParams.get('welcome')
  
  const [currentUser, setCurrentUser] = useState<User | null>(null)
  const [projects, setProjects] = useState<Project[]>([])
  const [projectStats, setProjectStats] = useState<Record<number, ProjectStats>>({})
  const [selectedProject, setSelectedProject] = useState<Project | null>(null)
  const [projectMembers, setProjectMembers] = useState<User[]>([])
  const [isSidebarOpen, setIsSidebarOpen] = useState(true)
  const [isNewProjectModalOpen, setIsNewProjectModalOpen] = useState(false)
  const [isEditProjectModalOpen, setIsEditProjectModalOpen] = useState(false)
  const [isUserDropdownOpen, setIsUserDropdownOpen] = useState(false)
  const [workload, setWorkload] = useState<WorkloadTodo[]>([])
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    fetchCurrentUser()
    fetchProjects()
    fetchWorkload()
  }, [])

  useEffect(() => {
    if (selectedProject) {
      fetchProjectMembers(selectedProject.id)
    }
  }, [selectedProject])

  // 点击外部区域关闭用户下拉菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Element
      if (isUserDropdownOpen && !target.closest('.user-dropdown')) {
        setIsUserDropdownOpen(false)
      }
    }

    document.addEventListener('mousedown', handleClickOutside)
    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [isUserDropdownOpen])

  const fetchCurrentUser = async () => {
    try {
      const response = await fetch('/api/user/me')
      if (response.ok) {
        const user = await response.json()
        setCurrentUser(user)
        setError(null) // 清除错误
      } else {
        const errorData = await response.json()
        if (errorData.casdoorError) {
          // Casdoor相关错误，显示用户友好的错误信息
          setError(`认证服务暂时不可用：${errorData.error}\n\n请检查网络连接或联系管理员。`)
          // 可以选择重定向到登录页面
          setTimeout(() => {
            router.push('/auth/login')
          }, 3000) // 3秒后重定向
        } else {
          // 其他错误
          console.error('获取当前用户失败:', errorData.error)
          setError('获取用户信息失败')
        }
      }
    } catch (err) {
      console.error('获取当前用户失败:', err)
      // 网络错误或其他异常
      setError('无法连接到服务器，请检查网络连接后重试。')
    }
  }

  const fetchProjects = async () => {
    try {
      const response = await fetch('/api/projects')
      if (response.ok) {
        const projectsData = await response.json()
        setProjects(projectsData)
        // 获取每个项目的统计信息
        await fetchProjectsStats(projectsData)
        // 默认选择第一个未归档的项目
        const firstActiveProject = projectsData.find((p: Project) => !p.isArchived)
        if (firstActiveProject) {
          setSelectedProject(firstActiveProject)
        }
      }
    } catch (err) {
      console.error('获取项目列表失败:', err)
    }
  }

  const fetchWorkload = async () => {
    try {
      const response = await fetch('/api/workload')
      if (response.ok) {
        const data = await response.json()
        setWorkload(data.workload || [])
      }
    } catch (err) {
      console.error('获取workload失败:', err)
    }
  }

  const fetchProjectsStats = async (projects: Project[]) => {
    const statsPromises = projects.map(async (project) => {
      try {
        const response = await fetch(`/api/projects/${project.id}/stats`)
        if (response.ok) {
          const stats = await response.json()
          return { projectId: project.id, stats }
        }
      } catch (err) {
        console.error(`获取项目 ${project.name} 统计失败:`, err)
      }
      return null
    })

    const results = await Promise.all(statsPromises)
    const statsMap: Record<number, ProjectStats> = {}
    
    results.forEach((result) => {
      if (result) {
        statsMap[result.projectId] = result.stats
      }
    })
    
    setProjectStats(statsMap)
  }

  const fetchProjectMembers = async (projectId: number) => {
    try {
      const response = await fetch(`/api/projects/${projectId}/members`)
      if (response.ok) {
        const membersData = await response.json()
        setProjectMembers(membersData)
      }
    } catch (err) {
      console.error('获取项目成员失败:', err)
    }
  }

  const handleNewProjectSuccess = () => {
    setIsNewProjectModalOpen(false)
    fetchProjects() // 重新获取项目列表
    fetchWorkload() // 重新获取workload
  }

  const handleEditProjectClick = () => {
    if (selectedProject) {
      setIsEditProjectModalOpen(true)
    }
  }

  const handleEditProjectSuccess = () => {
    setIsEditProjectModalOpen(false)
    fetchProjects() // 重新获取项目列表
    fetchWorkload() // 重新获取workload
  }

  const handleLogout = async () => {
    try {
      await fetch('/api/auth/logout', { method: 'POST' })
      router.push('/')
    } catch (err) {
      console.error('登出失败:', err)
    }
  }

  // 按状态分组workload
  const groupedWorkload = workload.reduce((acc, todo) => {
    if (!acc[todo.status]) {
      acc[todo.status] = []
    }
    acc[todo.status].push(todo)
    return acc
  }, {} as Record<string, WorkloadTodo[]>)

  // 状态emoji映射
  const statusEmoji = {
    '待完成': '📝',
    '进行中': '💪',
    '待测试': '🧪',
    '已完成': '✅'
  }

  return (
    <div className="min-h-screen bg-gray-100 flex">
      {/* 使用通用的ProjectSidebar组件 */}
      <ProjectSidebar
        isOpen={isSidebarOpen}
        onClose={() => setIsSidebarOpen(false)}
        showNewProjectButton={false}
        showBackToDashboard={false}
      />

      {/* 主内容区 */}
      <div className={`flex-1 transition-all duration-300 ease-in-out ${isSidebarOpen ? 'md:ml-64' : 'ml-0'}`}>
        <div className="bg-white shadow">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex justify-between items-center py-6">
              <div className="flex items-center flex-1">
                <button
                  onClick={() => setIsSidebarOpen(!isSidebarOpen)}
                  className="mr-4 text-gray-600 hover:text-gray-900"
                >
                  {isSidebarOpen ? <XMarkIcon className="h-6 w-6" /> : <Bars3Icon className="h-6 w-6" />}
                </button>
                <div className="flex-1">
                  <h1 className="text-3xl font-bold text-gray-900">仪表板</h1>
                  <p className="text-gray-600 mt-1">管理您的项目和任务</p>
                </div>
              </div>
              <div className="flex items-center space-x-3">
                <button 
                  onClick={() => setIsNewProjectModalOpen(true)}
                  className="text-white font-bold py-2 px-4 rounded flex items-center"
                  style={{ 
                    backgroundColor: currentUser?.color || '#4F46E5'
                  }}
                  onMouseEnter={(e) => {
                    if (currentUser?.color) {
                      e.currentTarget.style.backgroundColor = `${currentUser.color}CC`
                    }
                  }}
                  onMouseLeave={(e) => {
                    if (currentUser?.color) {
                      e.currentTarget.style.backgroundColor = currentUser.color
                    }
                  }}
                >
                  <PlusIcon className="h-5 w-5 mr-2" /> 新建项目
                </button>
                
                {/* 用户下拉菜单 */}
                {currentUser && (
                  <div className="relative user-dropdown">
                    <button
                      onClick={() => setIsUserDropdownOpen(!isUserDropdownOpen)}
                      className="flex items-center space-x-2 bg-white border border-gray-300 rounded-lg px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                      <div 
                        className="w-8 h-8 rounded-full border-2 border-white shadow-sm"
                        style={{ backgroundColor: currentUser.color }}
                      ></div>
                      <span className="hidden sm:block">{currentUser.name}</span>
                      <ChevronDownIcon className="h-4 w-4 text-gray-400" />
                    </button>
                    
                    {isUserDropdownOpen && (
                      <div className="absolute right-0 mt-2 w-64 bg-white rounded-md shadow-lg ring-1 ring-black ring-opacity-5 z-50">
                        <div className="py-1">
                          <div className="px-4 py-3 border-b border-gray-100">
                            <div className="flex items-center">
                              <div 
                                className="w-10 h-10 rounded-full border-2 border-white shadow-sm mr-3"
                                style={{ backgroundColor: currentUser.color }}
                              ></div>
                              <div>
                                <p className="text-sm font-medium text-gray-900">{currentUser.name}</p>
                                <p className="text-sm text-gray-500">{currentUser.email}</p>
                              </div>
                            </div>
                          </div>
                          <button
                            onClick={handleLogout}
                            className="block w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50"
                          >
                            登出
                          </button>
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
        
        <div className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8 w-full">
          <div className="px-4 py-6 sm:px-0">
            {/* 错误显示 */}
            {error && (
              <div className="mb-6 bg-red-50 border border-red-200 rounded-md p-4">
                <div className="flex">
                  <div className="flex-shrink-0">
                    <svg className="h-5 w-5 text-red-400" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                    </svg>
                  </div>
                  <div className="ml-3">
                    <h3 className="text-sm font-medium text-red-800">
                      连接错误
                    </h3>
                    <div className="mt-2 text-sm text-red-700">
                      <p className="whitespace-pre-line">{error}</p>
                    </div>
                  </div>
                </div>
              </div>
            )}
            
            {/* 欢迎消息 */}
            {welcome && (
              <div className="mb-6 bg-green-50 border border-green-200 rounded-md p-4">
                <div className="flex">
                  <div className="flex-shrink-0">
                    <svg className="h-5 w-5 text-green-400" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                    </svg>
                  </div>
                  <div className="ml-3">
                    <p className="text-sm text-green-800">
                      🎉 欢迎使用TODO List！您已成功注册并登录。
                    </p>
                  </div>
                </div>
              </div>
            )}
            
            <div className="border-4 border-dashed border-gray-200 rounded-lg p-8">
              <div className="flex justify-between items-center mb-8">
                <div className="flex items-center">
                  <button
                    onClick={() => setIsSidebarOpen(!isSidebarOpen)} 
                    className="text-gray-500 hover:text-gray-600 focus:outline-none focus:text-gray-600 mr-4"
                  >
                    {isSidebarOpen ? <XMarkIcon className="h-6 w-6" /> : <Bars3Icon className="h-6 w-6" />}
                  </button>
                  <h1 className="text-3xl font-bold text-gray-900">📊 仪表板</h1>
                </div>
                <div className="flex items-center space-x-4">
                  <button
                    onClick={() => setIsNewProjectModalOpen(true)}
                    className="text-white font-bold py-2 px-4 rounded transition duration-150 ease-in-out flex items-center"
                    style={{ 
                      backgroundColor: currentUser?.color || '#4F46E5'
                    }}
                    onMouseEnter={(e) => {
                      if (currentUser?.color) {
                        e.currentTarget.style.backgroundColor = `${currentUser.color}CC`
                      }
                    }}
                    onMouseLeave={(e) => {
                      if (currentUser?.color) {
                        e.currentTarget.style.backgroundColor = currentUser.color
                      }
                    }}
                  >
                    <PlusIcon className="h-5 w-5 mr-2" /> 新建项目
                  </button>
                </div>
              </div>

              {/* 项目概览 */}
              {projects.filter(p => !p.isArchived).length > 0 && (
                <div className="mt-8 bg-white shadow overflow-hidden sm:rounded-lg">
                  <div className="px-4 py-5 sm:px-6">
                    <h3 className="text-lg leading-6 font-medium text-gray-900">
                      项目概览
                    </h3>
                    <p className="mt-1 max-w-2xl text-sm text-gray-500">
                      您参与的当前项目及其进度情况
                    </p>
                  </div>
                  <div className="border-t border-gray-200">
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 p-6">
                      {projects.filter(p => !p.isArchived).map((project) => {
                        const stats = projectStats[project.id];
                        return (
                          <div key={project.id} className="rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow duration-200 flex flex-col bg-white">
                            <div 
                              className="p-4"
                              style={{ backgroundColor: currentUser?.color || '#4F46E5' }}
                            >
                              <h4 className="text-lg font-medium text-white truncate">
                                {project.name}
                              </h4>
                            </div>
                            <div className="p-4 flex-grow">
                              {stats ? (
                                <div className="space-y-3 flex flex-col h-full">
                                  <div className="flex justify-between text-sm">
                                    <span className="text-gray-600">完成进度</span>
                                    <span className="font-medium text-gray-900">
                                      {stats.已完成} / {stats.total} ({stats.completionRate}%)
                                    </span>
                                  </div>
                                  
                                  <div className="w-full bg-gray-200 rounded-full h-2.5">
                                    <div 
                                      className="bg-green-500 h-2.5 rounded-full"
                                      style={{ width: `${stats.completionRate}%` }}
                                    ></div>
                                  </div>
                                  
                                  <div className="grid grid-cols-2 gap-2 text-xs pt-2 flex-grow">
                                    <div className="flex justify-between">
                                      <span className="text-gray-500">📝 待完成:</span>
                                      <span className="font-medium">{stats.待完成}</span>
                                    </div>
                                    <div className="flex justify-between">
                                      <span className="text-blue-600">💪 进行中:</span>
                                      <span className="font-medium">{stats.进行中}</span>
                                    </div>
                                    <div className="flex justify-between">
                                      <span className="text-yellow-600">🧪 待测试:</span>
                                      <span className="font-medium">{stats.待测试}</span>
                                    </div>
                                    <div className="flex justify-between">
                                      <span className="text-green-600">✅ 已完成:</span>
                                      <span className="font-medium">{stats.已完成}</span>
                                    </div>
                                  </div>
                                  
                                  <a
                                    href={`/${encodeURIComponent(project.name)}/todolist`}
                                    className="block text-center text-sm font-semibold text-indigo-600 hover:text-indigo-800 pt-2"
                                  >
                                    查看详情
                                  </a>
                                </div>
                              ) : (
                                <div className="flex items-center justify-center h-full">
                                  <p className="text-sm text-gray-500">
                                    加载统计数据中...
                                  </p>
                                </div>
                              )}
                            </div>
                          </div>
                        )
                      })}
                    </div>
                  </div>
                </div>
              )}

              {/* Workload块 */}
              {workload.length > 0 && (
                <div className="mt-8 bg-white shadow overflow-hidden sm:rounded-lg">
                  <div className="px-4 py-5 sm:px-6">
                    <h3 className="text-lg leading-6 font-medium text-gray-900">
                      📋 工作负载 (Workload)
                    </h3>
                    <p className="mt-1 max-w-2xl text-sm text-gray-500">
                      待处理的高优先级任务概览
                    </p>
                  </div>
                  <div className="border-t border-gray-200">
                    <div className="p-6">
                      <div className="space-y-4">
                        {Object.entries(groupedWorkload).map(([status, todos]) => (
                          <div key={status} className="mb-6">
                            <div className="font-semibold text-gray-800 mb-3 text-lg">
                              {statusEmoji[status as keyof typeof statusEmoji] || '📋'} {status}：
                            </div>
                            <div className="space-y-3">
                              {todos.map((todo, index) => (
                                <div 
                                  key={todo.id} 
                                  className="rounded-lg p-4 shadow-sm border border-gray-200 hover:shadow-md transition-shadow duration-200"
                                  style={{ 
                                    backgroundColor: currentUser?.color ? `${currentUser.color}08` : '#f8fafc'
                                  }}
                                >
                                  <div className="flex items-start justify-between">
                                    <div className="flex-1">
                                      <div className="flex items-center mb-2">
                                        <span className="text-gray-500 mr-3 font-mono text-sm">{index + 1}.</span>
                                        <span className="font-bold text-gray-900 text-base">{todo.content}</span>
                                      </div>
                                      
                                      {todo.tags && (
                                        <div className="flex flex-wrap gap-2 mb-3">
                                          {todo.tags.split(/[,\s]+/).map((tag, tagIndex) => (
                                            <span
                                              key={tagIndex}
                                              className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                                              style={{
                                                backgroundColor: currentUser?.color ? `${currentUser.color}20` : '#dbeafe',
                                                color: currentUser?.color ? currentUser.color : '#1d4ed8'
                                              }}
                                            >
                                              {tag.trim()}
                                            </span>
                                          ))}
                                        </div>
                                      )}
                                      
                                      <div className="flex flex-wrap items-center gap-4 text-xs text-gray-500">
                                        <div className="flex items-center">
                                          <span className="mr-1">📁</span>
                                          <span>{todo.project_name}</span>
                                        </div>
                                        <div className="flex items-center">
                                          <span className="mr-1">👤</span>
                                          <span>{todo.creator_name}</span>
                                        </div>
                                        {todo.assignee_name && (
                                          <div className="flex items-center">
                                            <span className="mr-1">🎯</span>
                                            <span>分配给: {todo.assignee_name}</span>
                                          </div>
                                        )}
                                        <div className="flex items-center">
                                          <span className="mr-1">📅</span>
                                          <span>{new Date(todo.created_at).toLocaleDateString('zh-CN')}</span>
                                        </div>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                              ))}
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {/* 项目选择和管理 */}
              <div className="mt-8 grid grid-cols-1 lg:grid-cols-2 gap-8">
                <div className="bg-white rounded-lg shadow p-6">
                  <h2 className="text-xl font-semibold text-gray-900 mb-4">当前项目</h2>
                  
                  {/* 项目选择下拉菜单 */}
                  <div className="mb-4">
                    <label htmlFor="project-select" className="block text-sm font-medium text-gray-700 mb-2">
                      选择项目
                    </label>
                    <select
                      id="project-select"
                      value={selectedProject?.id || ''}
                      onChange={(e) => {
                        const projectId = parseInt(e.target.value)
                        const project = projects.find(p => p.id === projectId)
                        setSelectedProject(project || null)
                      }}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                    >
                      <option value="">请选择项目</option>
                      {projects.filter(p => !p.isArchived).map((project) => (
                        <option key={project.id} value={project.id}>
                          {project.name}
                        </option>
                      ))}
                    </select>
                  </div>

                  {/* 项目信息 */}
                  {selectedProject && (
                    <div className="bg-gray-50 rounded-lg p-4 mb-4">
                      <h3 className="text-lg font-medium text-gray-900 mb-2">{selectedProject.name}</h3>
                      <p className="text-gray-600 mb-3">{selectedProject.description}</p>
                      
                      {/* 项目成员 */}
                      <div className="mb-3">
                        <h4 className="text-sm font-medium text-gray-700 mb-2">项目成员</h4>
                        <div className="flex flex-wrap gap-2">
                          {projectMembers.map((member) => (
                            <span
                              key={member.id}
                              className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-800"
                            >
                              <span 
                                className="w-2 h-2 rounded-full mr-1" 
                                style={{ backgroundColor: member.color }}
                              ></span>
                              {member.name}
                            </span>
                          ))}
                        </div>
                      </div>

                      {/* 项目管理按钮 */}
                      <div className="flex space-x-2">
                        <button
                          onClick={handleEditProjectClick}
                          className="text-white font-bold py-2 px-4 rounded flex items-center text-sm"
                          style={{ 
                            backgroundColor: currentUser?.color || '#4F46E5'
                          }}
                          onMouseEnter={(e) => {
                            if (currentUser?.color) {
                              e.currentTarget.style.backgroundColor = `${currentUser.color}CC`
                            }
                          }}
                          onMouseLeave={(e) => {
                            if (currentUser?.color) {
                              e.currentTarget.style.backgroundColor = currentUser.color
                            }
                          }}
                        >
                          <PlusIcon className="h-4 w-4 mr-1" /> 编辑项目
                        </button>
                        <button
                          onClick={() => router.push(`/${encodeURIComponent(selectedProject.name)}/todolist`)}
                          className="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded text-sm"
                        >
                          进入项目
                        </button>
                      </div>
                    </div>
                  )}

                  {!selectedProject && (
                    <div className="text-center py-8 text-gray-500">
                      <p>请选择一个项目来查看详细信息</p>
                    </div>
                  )}
                </div>

                {/* 项目统计 */}
                <div className="bg-white rounded-lg shadow p-6">
                  <h2 className="text-xl font-semibold text-gray-900 mb-4">项目统计</h2>
                  <div className="grid grid-cols-2 gap-4">
                    <div 
                      className="rounded-lg p-4"
                      style={{ 
                        backgroundColor: currentUser?.color ? `${currentUser.color}20` : '#EFF6FF'
                      }}
                    >
                      <div 
                        className="text-2xl font-bold"
                        style={{ 
                          color: currentUser?.color || '#2563EB'
                        }}
                      >
                        {projects.filter(p => !p.isArchived).length}
                      </div>
                      <div 
                        className="text-sm"
                        style={{ 
                          color: currentUser?.color || '#2563EB'
                        }}
                      >
                        当前项目
                      </div>
                    </div>
                    <div className="bg-gray-50 rounded-lg p-4">
                      <div className="text-2xl font-bold text-gray-600">
                        {projects.filter(p => p.isArchived).length}
                      </div>
                      <div className="text-sm text-gray-600">归档项目</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 新建项目模态框 */}
      <NewProjectModal
        isOpen={isNewProjectModalOpen}
        onClose={() => setIsNewProjectModalOpen(false)}
        onSuccess={handleNewProjectSuccess}
      />

      {/* 编辑项目模态框 */}
      <NewProjectModal
        isOpen={isEditProjectModalOpen}
        onClose={() => setIsEditProjectModalOpen(false)}
        onSuccess={handleEditProjectSuccess}
        editMode={true}
        project={selectedProject}
      />
    </div>
  )
}